/**
 * @param {number} numCourses
 * @param {number[][]} prerequisites
 * @return {boolean}
 */

function canFinish(numCourses, prerequisites) {
  // 初始化邻接表和入度数组
  const adjList = new Array(numCourses).fill(0).map(() => []);
  const inDegree = new Array(numCourses).fill(0);

  // 构建邻接表和入度数组
  for (const [course, prereq] of prerequisites) {
    adjList[prereq].push(course); // prereq -> course
    inDegree[course]++;
  }

  // 初始化队列，将所有入度为0的课程加入队列
  const queue = [];
  for (let i = 0; i < numCourses; i++) {
    if (inDegree[i] === 0) {
      queue.push(i);
    }
  }

  let count = 0; // 记录已处理的课程数

  // BFS
  while (queue.length > 0) {
    const current = queue.shift();
    count++;

    // 遍历当前课程的后继课程
    for (const neighbor of adjList[current]) {
      inDegree[neighbor]--;
      if (inDegree[neighbor] === 0) {
        queue.push(neighbor);
      }
    }
  }

  // 如果所有课程都被处理，则无环；否则有环
  return count === numCourses;
}

// 测试示例
console.log(canFinish(2, [[1, 0]])); // true
console.log(
  canFinish(2, [
    [1, 0],
    [0, 1],
  ])
); // false
